package com.wswy.wzcx.ui.car

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.text.InputType
import android.text.TextUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.CarInfoModel
import com.wswy.wzcx.model.OCRResult
import com.wswy.wzcx.module.base.CBaseActivity
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.dialog.LoadingDialog
import com.wswy.wzcx.ui.keyboard.CarNoToolLayout
import com.wswy.wzcx.utils.FileUtils
import com.wswy.wzcx.utils.UiUtils
import com.wswy.wzcx.utils.fillText
import kotlinx.android.synthetic.main.activity_add_car_pre.*
import kotlin.math.min

/**
 * 添加车辆
 */
class AddCarPreActivity : CBaseActivity() {

    companion object {
        private const val TAG = "AddCarPreActivity"

        private const val REQUEST_CODE_DRIVING_LICENSE = 103

    }


    private lateinit var carNoKeyboard: CarNoToolLayout

    private lateinit var addCarPreViewModel: AddCarPreViewModel

    private var loadingDialog: LoadingDialog? = null


    private val carNoDiscernDialog: CarNoDiscernDialog by lazy {
        CarNoDiscernDialog(this).apply {

            onStartPhoto = {

                startActivityForResult(it, REQUEST_CODE_DRIVING_LICENSE)

                StatTools.sendClick(applicationContext, StatisticsId.clickOrcInNewAddCar)

            }

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_car_pre)

        addCarPreViewModel = provideViewModel(AddCarPreViewModel::class.java)

        addCarPreViewModel.onCreate()

        //关闭
        img_close.onClick {
            finish()
        }

        //拍照识别
        img_take_photo_car_no.onClick {

            StatTools.sendClick(applicationContext,StatisticsId.addcar_photo)

            carNoDiscernDialog.show()

        }

        //查询
        btn_query.onClick {
            doQuery()
        }

        tv_car_no_province.setOnClickListener {
            showKeyBoard(true)
        }

        //点击输入框
        et_car_no.setOnClickListener {
            showKeyBoard()

        }

        et_car_no.setOnTouchListener { v, event ->

            val inputType = et_car_no.inputType
            et_car_no.inputType = InputType.TYPE_NULL
            et_car_no.onTouchEvent(event)


            et_car_no.inputType = inputType

            showKeyBoard()

            val idx = et_car_no.getOffsetForPosition(event.x,event.y)
            val len = et_car_no.text?.length?:0
            if (idx >= 0 && len >= 0){
                et_car_no.setSelection(min(idx,len))
            }

            true
        }

        //最大长度
        et_car_no.filters = arrayOf(InputFilter.LengthFilter(7))


        addCarPreViewModel.getDefaultCarNoProvLiveData().observe(this, Observer {
            it?.run {


                if (TextUtils.isEmpty(et_car_no.text) && length == 1){
                    //还没有输入车牌号

                    tv_car_no_province.text = this
                }

            }

        })

        addCarPreViewModel.getOcrResultLiveData().observe(this, Observer {

            it?.let { data ->

                if (data.inLoading()) {
                    loadingDialog?.setOnDismissListener(null)
                    loadingDialog?.dismiss()

                    loadingDialog = LoadingDialog(this, "识别中").also {

                        it.show()
                    }

                } else if (data.isOk()) {

                    loadingDialog?.let { dialog ->

                        if (data.data?.ocrSuccess() == true){

                            dialog.setOnDismissListener { _ ->
                                carNoDiscernDialog.dismiss()

                                toNext(data.data)
                            }

                            dialog.setSuccess("识别成功")
                        }else{
                            dialog.setSuccess("识别失败")
                        }

                    }

                } else {
                    loadingDialog?.setSuccess(data.message)
                }


            }

        })

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == REQUEST_CODE_DRIVING_LICENSE && resultCode == Activity.RESULT_OK) {
            addCarPreViewModel.scannerOCR(FileUtils.getSaveFile(applicationContext).absolutePath)
        }

    }


    override fun onBackPressed() {

        if (::carNoKeyboard.isInitialized && carNoKeyboard.isShowing()) {
            carNoKeyboard.hide()
        } else {
            super.onBackPressed()
        }
    }


    private fun showKeyBoard(showProvince: Boolean = false) {

        if (!::carNoKeyboard.isInitialized) {
            viewstub_keyboard.inflate()

            carNoKeyboard = findViewById(R.id.ll_keyboard)

            carNoKeyboard.provincesClick = {
                tv_car_no_province.text = it
                et_car_no.requestFocus()
            }

            carNoKeyboard.alphabetClick = {

                carNoKeyboard.append(et_car_no,it,7)

            }

            val point = IntArray(2)
            btn_query.getLocationInWindow(point)


            val offsetH = layout_root.bottom - point[1] - UiUtils.getStatusBarHeight(applicationContext)

            var anim = false

            carNoKeyboard.onHeightOffset = { maxHeight, isShow, offset ->


                if (!anim && maxHeight > offsetH) {
                    anim = true

                    val y = if (isShow) -(maxHeight - offsetH).toFloat() else 0f

                    ll_content.animate().run {
                        translationY(y)
                        duration = 100
                        start()
                    }

                }

                if ((isShow && offset == 0f) || (!isShow && maxHeight.toFloat() == offset)) {
                    anim = false
                }

            }

            carNoKeyboard.deleteClick = { isLongPress ->

                carNoKeyboard.delete(et_car_no,isLongPress)

            }

        }

        carNoKeyboard.show(showProvince,false)
    }


    private fun toNext(ocrResult: OCRResult?) {

        ocrResult?.convert2CarInfo()?.let {

            it.province?.let {
                tv_car_no_province.text = it
            }
            et_car_no.fillText(it.noWithoutProvince)

            it.ocrResult = ocrResult.ocrItems

            AddCarInfoActivity.start(this,it)

            finish()
        }

        if (::carNoKeyboard.isInitialized && carNoKeyboard.isShowing()) {
            carNoKeyboard.hide()
        }
    }

    private fun doQuery(){

        if (et_car_no.text?.length?:0 >= 6 ){
            AddCarInfoActivity.start(this,CarInfoModel().apply {
                carNo = "${tv_car_no_province.text}${et_car_no.text}"
            })

            finish()

        }else{
            ToastUtils.showText("请输入完整车牌号")
        }

    }

}